package request

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

type Header []map[string]string

func Request(url string, params interface{}, contentType string) []byte {
	//超时时间：5秒
	client := &http.Client{Timeout: 5 * time.Second}
	jsonStr, _ := json.Marshal(params)
	fmt.Println("参数", string(jsonStr))
	resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	res, _ := ioutil.ReadAll(resp.Body)

	return res
}

// 简单直接的GET请求
func RequestGet(url string) []byte {
	//url = urlTools.QueryEscape(url)
	resp, err := http.Get(url)
	println("requestUrl", url)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		panic(err)
	}
	fmt.Println("===RequestGet===", string(body))
	return body
}

// POST请求 -- 使用http.Post()方法
// Tips：使用这个方法的话，第二个参数要设置成”application/x-www-form-urlencoded”，否则post参数无法传递。
func RequestPost(url string, param string) []byte {
	resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(param))
	if err != nil {
		fmt.Println(err)
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	//fmt.Println("===requestPost===", string(body))
	return body
}

// POST请求 -- 使用http.PostForm()方法
func RequestForm() []byte {
	resp, err := http.PostForm("http://www.baidu.com", url.Values{"key": {"Value"}, "id": {"123"}})

	if err != nil {
		panic(err)
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	//fmt.Println("===RequestForm===", string(body))
	return body
}

// 需要设置请求头
func RequestPostWithHeaders(url string, params string, headers Header) []byte {
	client := &http.Client{}

	req, err := http.NewRequest("POST", url, strings.NewReader(params))
	if err != nil {
		panic(err)
	}

	//设置请求头
	for _, header := range headers {
		for k, v := range header {
			req.Header.Set(k, v)
		}
	}

	// req.Header.Set("Cookie", "name=anny")

	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	//fmt.Println("===RequestPostWithHeaders===", string(body))
	return body
}
